﻿
// ProductCompareDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "ProductCompare.h"
#include "ProductCompareDlg.h"
#include "afxdialogex.h"
#include "io.h"
#include <regex> 
#include <string> 
#include <vector> 
#include <iostream> 
#include <stdio.h>
#include <msclr\marshal_cppstd.h>
#include <windows.h>
#include <mmsystem.h> // 加上，不然PlaySound函数无法使用
#pragma comment(lib, "WINMM.LIB") // 加上，不然PlaySound函数无法使用

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#using <mscorlib.dll>
#using "RegexMatchLib.dll"
using namespace RegexMatchLib;//换成dll中类所使用的namespace
#pragma managed

using namespace std;
using namespace std::tr1;

using namespace msclr::interop;
using namespace System;
int msg_c =0;  //m_msg字体颜色控制
int sound_flag = 0; //提示音控制

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};


UINT SoundThread(LPVOID)
{
	switch (sound_flag)
	{
	case 1:   //ConfirmError.wav
		PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
		break;
	case 2:	//ConfirmFinish.wav
		PlaySound(MAKEINTRESOURCE(IDR_WAVE2), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
		break;
	case 3: //ScanError.wav
		PlaySound(MAKEINTRESOURCE(IDR_WAVE3), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
		break;
	case 4: //ScanFinish.wav
		PlaySound(MAKEINTRESOURCE(IDR_WAVE4), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
		break;
	default:
		break;
	}

	return 0;
}

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CProductCompareDlg 对话框



CProductCompareDlg::CProductCompareDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(IDD_PRODUCTCOMPARE_DIALOG, pParent)
{
	m_bCheckLock = FALSE;
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

}

void CProductCompareDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_CHECK_Lock, m_ButtonCheckLock);
	DDX_Control(pDX, IDC_LISTTest, m_list);
	DDX_Control(pDX, IDC_EDIT_FILEPATH, m_filepath);
	DDX_Text(pDX, IDC_EDIT_CLotSN, m_CLotSN);
	DDX_Text(pDX, IDC_EDIT_OLotSN, m_OLotSN);
	DDX_Text(pDX, IDC_EDIT_OBarcode, m_OBarcode);
	DDX_Control(pDX, IDC_EDIT_MSG, m_msg);
	DDX_Control(pDX, IDC_STATIC_ERROR, m_error);
	DDX_Check(pDX, IDC_CHECK_Lock, m_bCheckLock);
}

BEGIN_MESSAGE_MAP(CProductCompareDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CTLCOLOR()
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON_SELECT, &CProductCompareDlg::OnBnClickedButtonSelect)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LISTTest, &CProductCompareDlg::OnLvnItemchangedListtest)

	ON_BN_CLICKED(IDC_CHECK_Lock, &CProductCompareDlg::OnBnClickedCheckLock)
	ON_BN_CLICKED(IDC_BUTTON_GetREG, &CProductCompareDlg::OnBnClickedButtonGetreg)
END_MESSAGE_MAP()


// CProductCompareDlg 消息处理程序

BOOL CProductCompareDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
	CProductCompareApp  *papp = (CProductCompareApp*)AfxGetApp();
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标


	m_list.ModifyStyle(LVS_TYPEMASK, LVS_REPORT);
	m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_FLATSB | LVS_EX_TWOCLICKACTIVATE | LVS_EX_GRIDLINES);
	m_list.InsertColumn(0, _T("序号"), LVCFMT_LEFT, 60);
	m_list.InsertColumn(1, _T("原厂型号"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(2, _T("客户型号"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(3, _T("品牌"), LVCFMT_LEFT, 200);
	papp->nItem = 0;

	GetDlgItem(IDC_EDIT_OLotSN)->EnableWindow(FALSE);
	GetDlgItem(IDC_EDIT_FILEPATH)->EnableWindow(FALSE);
	GetDlgItem(IDC_EDIT_REPPath)->EnableWindow(FALSE);

	m_ftCtrl.CreateFont(115,            // nHeight
		0,                         // nWidth
		0,                         // nEscapement
		0,                         // nOrientation
		FW_BOLD,                 // nWeight
		FALSE,                     // bItalic
		FALSE,                     // bUnderline
		0,                         // cStrikeOut
		DEFAULT_CHARSET,           // nCharSet
		OUT_DEFAULT_PRECIS,        // nOutPrecision
		CLIP_DEFAULT_PRECIS,       // nClipPrecision
		DEFAULT_QUALITY,           // nQuality
		DEFAULT_PITCH | FF_SWISS,  // nPitchAndFamily
		"黑体");

	GetDlgItem(IDC_EDIT_MSG)->SetFont(&m_ftCtrl);
	m_msg.SetWindowText("GO!!");


//	ShowWindow(SW_MINIMIZE);

	// TODO: 在此添加额外的初始化代码

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CProductCompareDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CProductCompareDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CProductCompareDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

HBRUSH CProductCompareDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
	CProductCompareApp  *papp = (CProductCompareApp*)AfxGetApp();                     //***** 生成指向运用程序类的指针*****

	if (pWnd->GetDlgCtrlID() == IDC_EDIT_MSG)
	{
	
		if (msg_c == 1)
		{
			pDC->SetTextColor(RGB(0, 255, 0));
		}
		else if  (msg_c == 2)
		{
			pDC->SetTextColor(RGB(255, 0, 0));
		}
		else
		{
			pDC->SetTextColor(RGB(0, 0, 255));
		}

	}
	if (pWnd->GetDlgCtrlID() == IDC_STATIC_ERROR)
	{
			pDC->SetTextColor(RGB(255, 0, 0));	
	}

	return hbr;
}

void CProductCompareDlg::OnBnClickedButtonSelect()
{
	// TODO: 在此添加控件通知处理程序代码
	//char FileName[_MAX_PATH];//设置最大路径值
	CProductCompareApp  *papp = (CProductCompareApp*)AfxGetApp();
	CString FileName;
	CString strFilter = _T("Excel文件(*.xls)|*.xls||");//文件过滤器(根据后缀名可以随便添加)
	CFileDialog FileOpenDlg(TRUE, _T("*.xls"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strFilter, NULL); //弹出打开对话框
	FileOpenDlg.m_ofn.lpstrTitle = _T("打开Excel文件");
	if (IDCANCEL == FileOpenDlg.DoModal())
	{
		AfxMessageBox(_T("未选择任何文件"));
		return; //打开失败
	}


	FileName = FileOpenDlg.GetPathName();//lstrcpy(FileName,FileOpenDlg.GetPathName()); //赋值文件全名(全路径+文件名)
	SetDlgItemText(IDC_EDIT_FILEPATH, FileName);
	m_list.DeleteAllItems();
	CString temp; 
	temp.Format(_T("%d"), papp->nItem);
	m_list.InsertItem(papp->nItem, temp);
	m_list.SetItemText(papp->nItem, 1, _T("Test"));
	m_list.SetItemText(papp->nItem, 2, _T("Test"));
	m_list.SetItemText(papp->nItem, 3, _T("Test"));
	ReadExcelBook(FileName);
	PlaySound(MAKEINTRESOURCE(IDR_WAVE4), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
}


void CProductCompareDlg::OnLvnItemchangedListtest(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	// TODO: 在此添加控件通知处理程序代码
	*pResult = 0;
}

////////////////////////////////////////////////////////////////////////  

///Function:    GetCellValue  

///Description: 得到的单元格在EXCEL中的字符串  

///Input:       row 单元格所在行  

///             col 单元格所在列  

///Return:      CString 单元格在EXCEL中的字符串  

//////////////////////////////////////////////////////////////////////// 

CString CProductCompareDlg::GetCellValue(int row, int col)

{
	range_temp = sheet.GetRange(COleVariant(IndexToString(row, col)), COleVariant(IndexToString(row, col)));
	COleVariant rValue;
	rValue = COleVariant(range_temp.GetValue2());
	rValue.ChangeType(VT_BSTR);
	return CString(rValue.bstrVal);

}
////////////////////////////////////////////////////////////////////////  

///Function:    IndexToString  

///Description: 得到的单元格在EXCEL中的定位名称字符串  

///Input:       row 单元格所在行  

///             col 单元格所在列  

///Return:      CString 单元格在EXCEL中的定位名称字符串  

////////////////////////////////////////////////////////////////////////  

CString CProductCompareDlg::IndexToString(int row, int col)

{
	CString strResult;
	if (col > 26)
	{
		strResult.Format(_T("%c%c%d"), 'A' + (col - 1) / 26 - 1, 'A' + (col - 1) % 26, row);
	}
	else
	{
		strResult.Format(_T("%c%d"), 'A' + (col - 1) % 26, row);
	}
	return strResult;
}

////////////////////////////////////////////////////////////////////////  

///Function:    initExcel  

///Description: 初始化COM ，判断excel版本

///Return:      成功 TRUE

////////////////////////////////////////////////////////////////////////  

BOOL CProductCompareDlg::initExcel()

{
	//if (!AfxOleInit()) {

	//	AfxMessageBox("初始化Ole出错！");

	//	return FALSE;

	//}

	if (!app.CreateDispatch(_T("Excel.Application")))

	{
		AfxMessageBox(_T("无法创建Excel应用！"));
		return FALSE;
	}

	CString strExcelVersion = app.GetVersion();
	/*if (_T("11.0") == strExcelVersion)

	//SetDlgItemText(IDC_STATXTCFG, "当前Excel的版本是2003。");

	AfxMessageBox(_T("当前Excel的版本是2003。"));

	else if (_T("12.0") == strExcelVersion)

	//fatsdlg.GetDlgItem(IDC_STATXTCFG)->SetWindowText(_T("当前Excel的版本是2007。"));

	AfxMessageBox(_T("当前Excel的版本是2007。"));

	else if (_T("14.0") == strExcelVersion)

	//SetDlgItemText(IDC_STATXTCFG, "当前Excel的版本是2010。");

	AfxMessageBox(_T("当前Excel的版本是2010。"));

	else

	AfxMessageBox(_T("当前Excel的版本是其他版本。"));*/
	//获取工作薄集合  

	//books = app.GetWorkbooks();

	//添加一个工作薄  

	//book = books.Add(covOptional);

	//获取工作表集合  

	//sheets = book.GetSheets();

	//获取第一个工作表  

	//sheet = sheets.GetItem(COleVariant((short)1));

	return TRUE;

}

////////////////////////////////////////////////////////////////////////  

///Function:    OpenExcelBook  

///Description: 打开excel对象 

///Input:       Excel_Path 文件路径

///Return:      成功 TRUE

////////////////////////////////////////////////////////////////////////  

BOOL CProductCompareDlg::OpenExcelBook(CString Excel_Path)

{
	CFileFind filefind;
	if (!filefind.FindFile(Excel_Path))
	{
		AfxMessageBox(_T("文件不存在"));
		return FALSE;
	}
	LPDISPATCH lpDisp; //接口指针  
	COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
	books = app.GetWorkbooks();
	lpDisp = books.Open(Excel_Path, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional, covOptional , covOptional, covOptional);          //与office 2000的不同，是个参数的，直接在后面加了两个covOptional成功了  
	book.AttachDispatch(lpDisp);
	sheets = book.GetSheets();
	sheet = sheets.GetItem(COleVariant((short)1));        //与的不同，是个参数的，直接在后面加了两个covOptional成功了  

	usedRange.AttachDispatch(sheet.GetUsedRange());
	rangeRow.AttachDispatch(usedRange.GetRows());
	rangeColumu.AttachDispatch(usedRange.GetColumns());
	return TRUE;
}

////////////////////////////////////////////////////////////////////////  

///Function:    ReadExcelBook  

///Description: 读取excel文件

///Input:       Excel_Path excel文件路径 

//////////////////////////////////////////////////////////////////////// 



bool CProductCompareDlg::ReadExcelBook(CString Excel_Path)
{
	CProductCompareApp  *papp = (CProductCompareApp*)AfxGetApp();
	CString strtemp;
	CString pro1, pro2, pro3;
	papp->nItem = 1;

		initExcel();

	//SetDlgItemText(IDC_STATXTCFG, "正在加载配置..."); 

	if (OpenExcelBook(Excel_Path))

	{
		iRowNum = rangeRow.GetCount();                     
		//已经使用的行数
		pop = new op_pr[iRowNum];

		for (int i = 2; i <= iRowNum; i++)
		{
			pro1 = GetCellValue(i, 1);  //原厂型号
			pro2 = GetCellValue(i, 3); //客户型号
			pro3 = GetCellValue(i, 2);  //品牌
			if ((pro1 != "") && (pro2 != ""))
			{
				strtemp.Format(_T("%d"), papp->nItem);
				m_list.InsertItem(papp->nItem, strtemp);
				m_list.SetItemText(papp->nItem, 1, pro1);
				m_list.SetItemText(papp->nItem, 2, pro2);
				m_list.SetItemText(papp->nItem, 3, pro3);
				pop[i - 1].row = papp->nItem;
				pop[i - 1].DOLotSN = pro1;
				pop[i - 1].DCLotSN = pro2;
				pop[i - 1].DBrand = pro3;
				iopNum = i - 1;
				papp->nItem++;
			}
		}
		m_list.DeleteItem(0);
		CloseExcelBook();
		return true;
	}
	else
		return false;
	//SetDlgItemText(IDC_STATXTCFG, "加载配置成功.");

}



////////////////////////////////////////////////////////////////////////  

///Function:    CloseExcelBook  

///Description: 释放excel对象   

//////////////////////////////////////////////////////////////////////// 

void CProductCompareDlg::CloseExcelBook()

{
	//释放对象（相当重要！） 

	rangeRow.ReleaseDispatch();

	rangeColumu.ReleaseDispatch();
	sheet.ReleaseDispatch();
	sheets.ReleaseDispatch();
	book.ReleaseDispatch();
	books.ReleaseDispatch();
	//退出程序   

	app.Quit();

	//m_ExlApp一定要释放，否则程序结束后还会有一个Excel进程驻留在内存中，而且程序重复运行的时候会出错   

	app.ReleaseDispatch();

}

BOOL CProductCompareDlg::PreTranslateMessage(MSG* pMsg)
{
	int		ret = -1;
	HWND	hWnd = ::GetFocus();
	int		mUserId = ::GetDlgCtrlID(hWnd);
	CString m_temp = _T("");

	// TODO: Add your specialized code here and/or call the base class	
	if (pMsg->message == WM_KEYDOWN)
	{
		if (pMsg->wParam == VK_ESCAPE) {
			return TRUE;
		}
		else if (pMsg->wParam == VK_RETURN)
		{
			UpdateData(true);

			switch (mUserId)
			{
			case IDC_EDIT_OBarcode:	
			{
				SetTimer(1, 1000, NULL);

				break;
			}
			case IDC_EDIT_CLotSN:		/*	保存扫描的设备SN	*/
			{

				if (m_OBarcode == "") {
					AfxMessageBox(_T("请扫描原厂条码！"));
					msg_c = 2;
					m_msg.SetWindowText("FAIL");
					GetDlgItem(IDC_EDIT_OBarcode)->SetFocus();
					m_OBarcode = "";
					PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
					break;
				}
				if (m_OLotSN == "") {
					AfxMessageBox(_T("请扫描原厂条码！"));
					msg_c = 2;
					m_msg.SetWindowText("FAIL");
					GetDlgItem(IDC_EDIT_OBarcode)->SetFocus();
					m_OBarcode = "";
					PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
					break;
				}
				if (m_CLotSN == "") {
					AfxMessageBox(_T("请扫描客户条码！"));
					msg_c = 2;
					m_msg.SetWindowText("FAIL");
					GetDlgItem(IDC_EDIT_CLotSN)->SetFocus();
					m_CLotSN = "";
					PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
					break;
				}
				bool resultCLotSN, resultLotSNCompare;

				resultCLotSN = opreadCLotSN();
				if (!resultCLotSN)
				{
					AfxMessageBox(_T("在excel表中未检索到该客户条码，请检查！"));
					msg_c = 2;
					m_msg.SetWindowText("FAIL");
					GetDlgItem(IDC_EDIT_CLotSN)->SetFocus();
					m_CLotSN = "";
					PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
					break;
				}
				resultLotSNCompare = opLotSNCompare();
				if (!resultLotSNCompare)
				{
					AfxMessageBox(_T("检索到该客户条码与原厂条码不对应，请检查！"));
					msg_c = 2;
					m_msg.SetWindowText("FAIL");
					GetDlgItem(IDC_EDIT_OBarcode)->SetFocus();

					CTime tm = CTime::GetCurrentTime();
					CString strtm = tm.Format("%Y-%m-%d");
					CString log;
					log.Format("%s,%s,%s,%s,%s", strtm, m_OBarcode, m_OLotSN, m_CLotSN, "FAIL");
					SaveTestLog((LPSTR)(LPCTSTR)log);

					m_CLotSN = "";
					m_OLotSN = "";
					m_OBarcode = "";
					PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
					break;
				}
				else
				{
					msg_c = 1;
					m_msg.SetWindowText("PASS");
					GetDlgItem(IDC_EDIT_OBarcode)->SetFocus();
					CTime tm = CTime::GetCurrentTime();
					CString strtm = tm.Format("%Y-%m-%d");
					CString log;
					log.Format("%s,%s,%s,%s,%s", strtm, m_OBarcode, m_OLotSN, m_CLotSN,"PASS");
					SaveTestLog((LPSTR)(LPCTSTR)log);
					m_CLotSN = "";
					m_OLotSN = "";
					m_OBarcode = "";
					PlaySound(MAKEINTRESOURCE(IDR_WAVE4), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);

				}
			}

				break;
			default:
				break;
			}

			UpdateData(false);

			return false;
		}
	}
	return CDialog::PreTranslateMessage(pMsg);
}
BOOL CProductCompareDlg::test_regex_match()
{
	try
	{
		string RegexCheck, b;
		b = m_OBarcode.GetBuffer(0);
		RegexCheck = m_RegexCheck.GetBuffer(0);
		std::regex pattern(RegexCheck);
		std::match_results<std::string::const_iterator> result;
		bool valid = regex_match(b, pattern);
		//此处result参数可有可无，result是一个字符串数组，用来存储正则表达式里面括号的内容。
		if (valid && (result.length() > 0))
		{
			for (int i = 0; i < result.length(); i++)
			{
				cout << result[i] << endl;
			}
		}
		return valid;
	}
	catch (const std::tr1::regex_error &e)
	{
		AfxMessageBox(_T(",请检查正则表达式是否符合规则！"));

		return false;
	}


}
BOOL CProductCompareDlg::test_regex_search()
{
	try
	{
		string RegexGet, b;
		b = m_OBarcode.GetBuffer(0);
		RegexGet = m_RegexGet.GetBuffer(0);
		std::regex pattern(RegexGet);
		string a="";
		std::regex re(pattern);
		std::string str{ b };
		std::smatch results;
		if (std::regex_search(str, results, re)) {
			for (auto x = results.begin(); x != results.end(); x++)
				a = a + x->str();
		}
		else
		{
			return false;
		}
		m_OLotSN.Format("%s", a.c_str());
		return true;
	}
	catch (const std::tr1::regex_error &e)
	{
		AfxMessageBox(e.what());
		AfxMessageBox(_T(",请检查正则表达式是否符合规则！"));

		return false;
	}
}

BOOL CProductCompareDlg::opreadOLotSN()
{
	for (int i = 1; i <= iopNum; i++)
	{
		if (pop[i].DOLotSN == m_OLotSN)
			return true;
	}
	return false;
}
BOOL CProductCompareDlg::opreadCLotSN()
{
	for (int i = 1; i <= iopNum; i++)
	{
		if (pop[i].DCLotSN == m_CLotSN)
			return true;
	}
	return false;
}

BOOL CProductCompareDlg::opLotSNCompare()
{
	for (int i = 1; i <= iopNum; i++)
	{
		if ((pop[i].DCLotSN == m_CLotSN) && (pop[i].DOLotSN == m_OLotSN))
			return true;
	}
	return false;
}

BOOL CProductCompareDlg::opreadBrand(CString Brand)
{
	for (int i = 1; i <= iopNum; i++)
	{
		if (pop[i].DBrand == Brand)
			return true;
	}
	return false;
}




void CProductCompareDlg::OnBnClickedCheckLock()
{
	// TODO: 在此添加控件通知处理程序代码
	CProductCompareApp  *papp = (CProductCompareApp*)AfxGetApp();               // ***** 生成指向运用程序类的指针*****
	UpdateData(TRUE);
	CString cstrHelp;
	if (m_bCheckLock)
	{
		GetDlgItem(IDC_BUTTON_GetREG)->EnableWindow(FALSE);
		GetDlgItem(IDC_BUTTON_SELECT)->EnableWindow(FALSE);
	}
	else
	{
		GetDlgItem(IDC_BUTTON_SELECT)->EnableWindow(TRUE);
		GetDlgItem(IDC_BUTTON_GetREG)->EnableWindow(TRUE);
	}
}

//文件监控类及socket通信日志保存
void CProductCompareDlg::SaveTestLog(char* Message)
{
	CTime tm = CTime::GetCurrentTime();
	CString strtm = tm.Format("%Y-%m-%d");
	strtm = _T("log_") + strtm + _T(".txt");

	FILE *fp;
	fp = fopen((LPSTR)(LPCTSTR)strtm, "a+");
	if (fp != NULL)
	{
		fprintf(fp, "%s\n", Message);
		fclose(fp);
	}
}


CString CProductCompareDlg::regex_match_methed(CString cstrRegexCheck, CString cstrOBarcode)
{
	System::String^ exp = marshal_as<String^>(cstrRegexCheck.GetBuffer());
	cstrRegexCheck.ReleaseBuffer();
	System::String^ str = marshal_as<String^>(cstrOBarcode.GetBuffer());
	cstrOBarcode.ReleaseBuffer();
	CString str_output;
	try {
	
		RegexMatchLib::RegexMatch ^pICalc = gcnew RegexMatchLib::Class1();
		System::String^ str_outputconv = gcnew String(str_output);
		//str_output = pICalc->RegexMatchMethed(b, RegexGet);
		str_output = str_output = pICalc->RegexMatchMethed(str, exp);
	}
	catch (...) {
		str_output = "";
	}
	return str_output;
}

void CProductCompareDlg::OnBnClickedButtonGetreg()
{
	// TODO: 在此添加控件通知处理程序代码
	CProductCompareApp  *papp = (CProductCompareApp*)AfxGetApp();
	CString FileName;
	CString strFilter = _T("Excel文件(*.xls)|*.xls||");//文件过滤器(根据后缀名可以随便添加)
	CFileDialog FileOpenDlg(TRUE, _T("*.xls"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strFilter, NULL); //弹出打开对话框
	FileOpenDlg.m_ofn.lpstrTitle = _T("打开Excel文件");
	if (IDCANCEL == FileOpenDlg.DoModal())
	{
		AfxMessageBox(_T("未选择任何文件"));
		return; //打开失败
	}


	FileName = FileOpenDlg.GetPathName();//lstrcpy(FileName,FileOpenDlg.GetPathName()); //赋值文件全名(全路径+文件名)
	SetDlgItemText(IDC_EDIT_REPPath, FileName);
	ReadExcelBookREP(FileName);
	prreadrepcheck();
	if (m_RegexCheck == "")
	{
		AfxMessageBox(_T("未检索搭到品号对应正则表达式规则，请检查"));
		return; //打开失败
	}
	PlaySound(MAKEINTRESOURCE(IDR_WAVE4), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
}

bool CProductCompareDlg::ReadExcelBookREP(CString Excel_Path)
{
	CString rep1, rep2, rep3;
	CProductCompareApp  *papp = (CProductCompareApp*)AfxGetApp();
	initExcel();

	//SetDlgItemText(IDC_STATXTCFG, "正在加载配置..."); 

	if (OpenExcelBook(Excel_Path))
	{
		iprRowNum = rangeRow.GetCount();
		//已经使用的行数
		pr = new pr_rep[iprRowNum];

		for (int i = 2; i <= iRowNum; i++)
		{
			rep1 = GetCellValue(i, 1);  //品牌
			rep2 = GetCellValue(i, 2); //正则表达式
			if ((rep1 != "") && (rep2 != ""))
			{

				pr[i - 1].row = i-1;
				pr[i - 1].DBrand = rep1;
				pr[i - 1].repcheck = rep2;
				iprNum = i - 1;
			}
		}
	
		CloseExcelBook();
		return true;
	}
	else
		return false;
	//SetDlgItemText(IDC_STATXTCFG, "加载配置成功.");

}

BOOL CProductCompareDlg::prreadrepcheck()
{
	for (int i = 1; i <= iprNum; i++)
	{
		if (pr[i].DBrand == pop[1].DBrand)
		{
			m_RegexCheck = pr[i].repcheck;
			return true;
		}
	}
	return false;
}
void CProductCompareDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default   
	switch (nIDEvent)
	{
	case 1:
		// 如果收到ID为1的定时器的消息则  
	{
		KillTimer(1);
		if (m_OBarcode == "") {
			AfxMessageBox(_T("请扫描原厂条码！"));
			msg_c = 2;
			m_msg.SetWindowText("FAIL");
			GetDlgItem(IDC_EDIT_OBarcode)->SetFocus();
			m_OBarcode = "";
			PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
			break;
		}
		for (int i = 1; i <= iprNum; i++)
		{
			if (opreadBrand(pr[i].DBrand))
			{
				m_OLotSN = regex_match_methed(pr[i].repcheck, m_OBarcode);
				if (m_OLotSN != "")
				{
					SetDlgItemText(IDC_EDIT_OLotSN, m_OLotSN);
					break;
				}
			}
			
		}

		if (m_OLotSN == "")
		{
			CString cstrhelp;
			cstrhelp.Format("条码匹配正则表达式pn点为空，请清空输入框后重新扫描！");
			m_error.SetWindowText(cstrhelp);
			msg_c = 2;
			m_msg.SetWindowText("FAIL");
			GetDlgItem(IDC_EDIT_OBarcode)->SetFocus();
			PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
			break;
		}
		bool resultOLotSN;
		resultOLotSN = opreadOLotSN();
		if (!resultOLotSN)
		{
			AfxMessageBox(_T("在excel表中未检索到该原厂型号，请检查！"));
			msg_c = 2;
			m_msg.SetWindowText("FAIL");
			GetDlgItem(IDC_EDIT_OBarcode)->SetFocus();
			m_OBarcode = "";
			m_OLotSN = "";
			PlaySound(MAKEINTRESOURCE(IDR_WAVE1), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
			break;
		}
		GetDlgItem(IDC_EDIT_CLotSN)->SetFocus();
		msg_c = 0;
		m_msg.SetWindowText("GO!!");
		m_error.SetWindowText("");
		PlaySound(MAKEINTRESOURCE(IDR_WAVE4), AfxGetResourceHandle(), SND_RESOURCE | SND_PURGE | SND_NODEFAULT);
	}
		break;
	case 2:
		// 如果收到ID为2的定时器的消息则  
		break;
	default:
		break;
	}
	CDialogEx::OnTimer(nIDEvent);
}